package com.ea.service.impl;

import com.alibaba.fastjson.JSON;
import com.ea.common.constant.BaseNumConstant;
import com.ea.common.constant.RedisKeyConstants;
import com.ea.common.enums.OperationResultCode;
import com.ea.common.exception.ServiceException;
import com.ea.common.util.RedisUtil;
import com.ea.common.util.TypeConversionToJson;
import com.ea.domain.dto.FlagDTO;
import com.ea.domain.entity.ElectricGoodsSkuInfo;
import com.ea.domain.query.FrontElectricGoodsQueryDTO;
import com.ea.domain.vo.ElectricGoodsVO;
import com.ea.domain.vo.ElectricGoodsSkuVO;
import com.ea.mapper.ElectricGoodsInfoMapper;
import com.ea.mapper.ElectricGoodsSkuInfoMapper;
import com.ea.mapper.SysBaseFlagMapper;
import com.ea.service.IFrontElectricGoodsInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author NAME-L
 * @Description TODO
 * @className IFrontElectricGoodsInfoServiceImpl
 * @date 2023-01-11 22:33:27
 */
@Service
public class IFrontElectricGoodsInfoServiceImpl implements IFrontElectricGoodsInfoService {

    private static final Logger logger = LoggerFactory.getLogger(IFrontElectricGoodsInfoServiceImpl.class);

    @Autowired
    private ElectricGoodsInfoMapper goodsInfoMapper;

    @Autowired
    private ElectricGoodsSkuInfoMapper skuInfoMapper;

    @Autowired
    private SysBaseFlagMapper flagMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public PageInfo<ElectricGoodsVO> getGoodsList(FrontElectricGoodsQueryDTO queryDTO) {
        Integer pageIndex = queryDTO.getPageIndex() == null ? BaseNumConstant.NUM_1 : queryDTO.getPageIndex();
        Integer pageSize = queryDTO.getPageSize() == null ? BaseNumConstant.NUM_20 : queryDTO.getPageSize();
        PageHelper.startPage(pageIndex, pageSize);
        // 根据条件查询出所有的货品信息
        List<ElectricGoodsVO> goodsInfoList = goodsInfoMapper.queryAllInfoListFront(queryDTO);
        List<Long> goodsIdList = goodsInfoList.stream().map(ElectricGoodsVO::getGoodsId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(goodsIdList)) {
            return new PageInfo<>();
        }
        List<ElectricGoodsSkuInfo> goodsSkuInfoList = skuInfoMapper.selectAllByGoodsIdBatch(goodsIdList);
        Set<Long> hasSkuGoodsIdList = goodsSkuInfoList.stream().map(ElectricGoodsSkuInfo::getGoodsId).collect(Collectors.toSet());
        goodsInfoList.removeIf(goods -> !hasSkuGoodsIdList.contains(goods.getGoodsId()));
        return new PageInfo<>(goodsInfoList);
    }

    @Override
    public Map<String, String> getSkuInfoByGoodsId(Long goodsId) {
        if (goodsId == null) {
            return new HashMap<>();
        }
        logger.info("要查询规格的货品为：{}", goodsId);
        List<ElectricGoodsSkuInfo> skuInfoList = skuInfoMapper.selectSkuByGoodsId(goodsId);
        if (CollectionUtils.isEmpty(skuInfoList)) {
            throw new ServiceException(OperationResultCode.GOODS_HAS_NO_SKU.getCode(), String.format(OperationResultCode.GOODS_HAS_NO_SKU.getMsg(), goodsId));
        }
        //将货品id放进redis作为热点缓存数据
        redisUtil.zIncrementScore(RedisKeyConstants.HOT_GOODS  , goodsId.toString(), 1);
        Map<String, String> skuInfoMap = skuInfoList.stream().collect(Collectors.toMap(k -> k.getSkuId().toString(), ElectricGoodsSkuInfo::getSkuName));
        if (MapUtils.isEmpty(skuInfoMap)) {
            throw new ServiceException(OperationResultCode.SYSTEM_ERROR);
        }
        return skuInfoMap;
    }


    @Override
    public ElectricGoodsSkuVO getSkuInfoBySkuId(Long skuId) {
        if (skuId == null) {
            throw new ServiceException(OperationResultCode.PARAMETER_ERROR);
        }
        ElectricGoodsSkuVO skuShowVO = skuInfoMapper.selectSkuDetailBySkuId(skuId);
        logger.info("IFrontElectricGoodsInfoServiceImpl.getSkuInfoBySkuId ====>{}", JSON.toJSONString(skuShowVO));
        if (skuShowVO == null) {
            throw new ServiceException(OperationResultCode.SYSTEM_ERROR);
        }
        String flagIds = skuShowVO.getFlagIds();
        List<Long> flagIdList = TypeConversionToJson.jsonToList(flagIds, Long.class);
        if (CollectionUtils.isNotEmpty(flagIdList)) {
            List<FlagDTO> flagDTOList = flagMapper.selectFlagByFlagIdList(flagIdList);
            skuShowVO.setFlagDTOList(flagDTOList);
        }
        return skuShowVO;
    }

    @Override
    public List<ElectricGoodsVO> getHotGoodsCache() {
        // 展示热榜前三的货品信息
        Set<Object> goodsObject = redisUtil.zReverseRange(RedisKeyConstants.HOT_GOODS, 0, 2);
        Iterator<Object> iterator = goodsObject.iterator();
        List<Long> goodsIdList = new ArrayList<>();
        List<ElectricGoodsVO> goodsShowVOList = new ArrayList<>();
        while (iterator.hasNext()) {
            goodsIdList.add( Long.valueOf(iterator.next().toString()));
        }
        if (CollectionUtils.isNotEmpty(goodsIdList)) {
            goodsShowVOList = goodsInfoMapper.selectGoodsShowVOByGoodsIdList(goodsIdList);
        }
        return goodsShowVOList;
    }

}
